package com.example.juc.big_talk_concurrent.chapter5.article1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        // 临界资源
        List<Integer> list = new ArrayList<>();

        // 使用同步锁保证两段临界代码同一时刻只会有一段在执行
        ReentrantLock lock = new ReentrantLock();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
//                    lock.lock();
                    list.add(i);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
//                    lock.unlock();
                }
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 10; i < 20; i++) {
//                    lock.lock();
                    list.add(i);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
//                    lock.unlock();
                }
            }
        }, "t2");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(list);
        // 输出结果，add方法不是原子方法，存在并发问题
        // [0, 10, 1, 11, 12, 2, 13, 3, 4, 14, null, 5, 16, 6, 17, 7, 8, 18, 9, 19]
    }

}
